package joindemo.sse.listener;

import joindemo.common.enums.HttpStatusEnum;
import joindemo.common.enums.MessageType;
import joindemo.domain.po.Message;
import joindemo.exception.ServiceException;
import joindemo.mapper.MessageMapper;
import joindemo.sse.event.SseEvent;
import joindemo.sse.util.SseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class SseEventListener {

    private static final String LIKE_MESSAGE="点赞了你的文章";

    private static final String COLLECT_MESSAGE="收藏了你的文章";

    private static final String COMMENT_MESSAGE="对你发送了一条评论";

    @Autowired
    private  MessageMapper messageMapper;


    @Async
    @EventListener(SseEvent.class)
    public void handleSseEvent(SseEvent event){
        Message message=Message.builder()
                .messageType(event.getMessageType())
                .articleId(event.getArticleId())
                .commentId(event.getCommentId())
                .isRead(false)
                .fromUserId(event.getFromUserId())
                .userId(event.getUserId())
                .build();
        if(message.getMessageType()== MessageType.LIKE){
            message.setContent(LIKE_MESSAGE);
        }else if(message.getMessageType()==MessageType.COLLECT){
            message.setContent(COLLECT_MESSAGE);
        }else if(message.getMessageType()==MessageType.COMMENT){
            message.setContent(COMMENT_MESSAGE);
        }else{
            throw new ServiceException(HttpStatusEnum.ERROR);
        }
        messageMapper.insert(message);
        String currentConnection=event.getUsername()+message.getContent();
        SseUtils.sendTestMessage(message.getUserId(),currentConnection);
    }
}
